import sys

from sqlalchemy import create_engine, String, Text
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
import os

# 获取当前路径
# 获取正确的数据库路径
# 获取正确的数据库路径
def get_db_path():
    """获取数据库文件路径"""
    # 如果是打包后的exe文件，使用exe文件所在目录
    if getattr(sys, 'frozen', False):
        # PyInstaller打包后的exe文件所在目录
        base_path = os.path.dirname(sys.executable)
    else:
        # 正常开发环境路径
        base_path = os.path.dirname(os.path.abspath(__file__))
    return os.path.join(base_path, "auto.db")
# 创建数据库引擎
db_path = get_db_path()
engine = create_engine(f"sqlite:///{db_path}", echo=True)

class Base(DeclarativeBase):
    pass

class AutoConfig(Base):
    __tablename__ = "auto_config"
    ckey: Mapped[str] = mapped_column(String(64), primary_key=True, comment="建名", nullable=False)
    cvalue: Mapped[str] = mapped_column(String(64), comment="建值", nullable=False)
    cdesc: Mapped[str] = mapped_column(String(64), comment="建描述", nullable=False)
    def __repr__(self):
        return f"<AutoConfig(ckey={self.ckey}, cvalue={self.cvalue}, cdesc={self.cdesc})>"
    def to_dict(self):
        return {
            "ckey": self.ckey,
            "cvalue": self.cvalue,
            "cdesc": self.cdesc
        }

# 创建英语单词表，包括单词，音标，释义，创建时间
class AutoWords(Base):
    __tablename__ = "auto_words"
    word: Mapped[str] = mapped_column(String(512), primary_key=True, comment="单词", nullable=False)
    pronunciation: Mapped[str] = mapped_column(String(512), comment="音标", nullable=False)
    meaning: Mapped[str] = mapped_column(Text, comment="释义", nullable=False)
    costs: Mapped[str] = mapped_column(String(128), comment="大模型响应时长", nullable=False)
    create_time: Mapped[str] = mapped_column(String(64), comment="创建时间", nullable=False)
    def __repr__(self):
        return f"<EnglishWord(word={self.word}, pronunciation={self.pronunciation}, meaning={self.meaning}, create_time={self.create_time})>"
    def to_dict(self):
        return {
            "word": self.word,
            "pronunciation": self.pronunciation,
            "meaning": self.meaning,
            "costs": self.costs,
            "create_time": self.create_time
        }


# 初始化数据库函数
def init_database():
    """初始化数据库和表"""
    try:
        # 确保数据库目录存在
        db_dir = os.path.dirname(db_path)
        os.makedirs(db_dir, exist_ok=True)

        Base.metadata.create_all(engine)
        print("数据库初始化成功")
    except Exception as e:
        print(f"数据库初始化失败: {e}")
        raise

# 确保数据库在模块导入时就初始化
if __name__ == "__main__":
    init_database()

"""
Base.metadata.drop_all(engine)
Base.metadata.create_all(engine)

AutoWords.metadata.drop_all(engine)
AutoWords.metadata.create_all(engine)
"""
